<template>
  <div>
    <m-container
      class="order"
      :pagination-visible="false"
      :current.sync="query.current"
      :size.sync="query.size"
      :total.sync="query.total"
    >
      <OrderForm slot="form" v-model="query" />
      <template slot="content">
        <el-tabs
          v-model="query.orderStatus"
          type="card"
          @tab-click="handleTabClick"
        >
          <el-tab-pane name="-1" style="padding:0 20px">
            <span slot="label">
              <div class="order__quickly" style="width:100px;">
                <span class="name">{{ quicklyName }}</span>
                <el-dropdown trigger="click" @click.native.stop>
                  <i class="el-icon-arrow-down el-icon--right"></i>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      v-for="item of quicklyOption"
                      @click.native="setQuicklyDate(item.value)"
                      :key="item.value"
                      >{{ item.label }}</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </span>
          </el-tab-pane>
          <el-tab-pane label="待付款" name="0"> </el-tab-pane>
          <el-tab-pane label="待发货" name="1"> </el-tab-pane>
          <el-tab-pane label="已完成" name="4"> </el-tab-pane>
          <el-tab-pane label="已关闭" name="5"> </el-tab-pane>
        </el-tabs>
      </template>
    </m-container>

    <OrderDetailModal
      v-model="detailVisible"
      :detail="orderDetail"
      :isGroup="true"
      @reset="handleSeeDetail"
    />

    <RemarkModal
      v-model="remarklVisible"
      :current-order="currentOrder"
      :orderIds="orderIds"
      title="备注"
      @onOk="handleRemarks"
      @onCancel="toggleRemarklVisible"
    />
  </div>
</template>

<script lang="ts">
import { Vue, Component, Watch } from "vue-property-decorator";
import OrderForm from "./components/OrderForm.vue";
import OrderDetailModal from "./components/detail/Index.vue";
import RemarkModal from "./components/RemarkModal.vue";
import { orderQuery, filterEmpty } from "./common/order";
import {
  getOrders,
  getOrderDetail,
  remarks,
  close,
} from "@/api/order";
import cloneDeep from "lodash/cloneDeep";
import { isClose } from "./common/order";

Component.registerHooks(["beforeRouteEnter", "beforeRouteUpdate"]);

/** 订单默认页 */
@Component({
  components: {
    OrderForm,
    OrderDetailModal,
    RemarkModal,
  },
})
export default class OrderHome extends Vue {
  /** 查询条件 */
  query = cloneDeep(orderQuery);


  /** tab[0]选项 */
  quicklyOption = [
    { label: "近一个月订单", value: "0" },
    { label: "近三个月订单", value: "1" },
    { label: "全部订单", value: "2" },
  ];

  /** 表格数据 */
  data = [];

  /** 选择的订单ID组 */
  orderIds = [];

  /** 订单详情modal */
  detailVisible = false;

  /** 留言modal */
  remarklVisible = false;

  /** 订单详情 */
  orderDetail = {};

  /** 表格选中条目 */
  checkedItem = [];

  /** 当前选中的订单 */
  currentOrder = null;

  get orders() {
    return this.data.map(item => {
      item.close = isClose(item.status);
      return item;
    });
  }

  /** 表格选中条目ID组 */
  get selectedIds() {
    return this.checkedItem.map(item => item.orderId);
  }

  get quicklyName() {
    return this.quicklyOption.find(
      item => item.value === this.query.quicklyDate,
    ).label;
  }

  get showDeliverId() {
    return this.$store.state.order.showDeliverId;
  }

  get sendBillVisible() {
    return this.query.orderStatus === "-1" || this.query.orderStatus === "1";
  }

  /** 监听query变化 */
  @Watch("query", { deep: true })
  handleQueryChange(v, ov) {
    this.getOrders(filterEmpty({ ov, ...filterEmpty(v) }));
  }

  beforeDestroy() {
    this.$store.dispatch("order/setShowDeliverId", "");
  }

  /** 获取订单 */
  created() {
    let params = {};
    if (this.showDeliverId) {
      params = {
        deliverId: this.showDeliverId,
        sendBillId: this.showDeliverId,
      };
      this.query.sendBillId = this.showDeliverId;
      this.query.deliverId = this.showDeliverId;
    }

    getOrders(filterEmpty(cloneDeep({ ...orderQuery, ...params })))
      .then(res => {
        const { list, ...other } = res.data;
        Object.assign(this.query, other);
        this.data = list;
      })
      .catch(() => {
        alert("列表获取失败,请稍后再试");
      });
  }

  /** 监听路由变化 更新数据 */
  // beforeRouteUpdate(to, form, next) {
  //   this.$set(this.query, "orderStatus", to.query.orderStatus);
  //   this.getOrders(
  //     filterEmpty(Object.assign(cloneDeep(orderQuery), to.query)),
  //     () => {
  //       next();
  //     },
  //   );
  // }

  /** 获取订单列表 */
  getOrders(q) {
    getOrders(q)
      .then(res => {
        const { list, ...other } = res.data;
        Object.assign(this.query, other);
        this.data = list;
        this.$nextTick(() => {
          this.$scrollTop(".admin__main--content");
        });
      })
      .catch(err => {
        this.$message.warning(err || "订单列表获取失败");
      });
  }

  /**
   * 监听table传来的事件
   * @param {name} 事件名 remark | close | detail
   */
  tableFunction(name, data) {
    switch (name) {
      case "remark":
        return this.triggerRemark(data);
      case "close":
        return this.handleClose(data);
      case "detail":
        return this.handleSeeDetail(data);
    }
  }

  handleTabClick({ name: orderStatus }) {
    Object.assign(this.query, {
      ...orderQuery,
      orderStatus,
      current: 1,
      deliverId: "",
      quicklyDate: this.query.quicklyDate,
    });
  }

  /**
   * 查看详情
   * @param {orderData} 订单数据 如果没有参数为批量操作
   */
  handleSeeDetail(orderData) {
    if (orderData.orderId) {
      this.toggleDetailModal();
    }

    getOrderDetail(orderData.orderId || orderData.id)
      .then(res => {
        this.orderDetail = res.data;
      })
      .catch(err => {
        this.$message.warning(err || "订单详情获取失败");
      });
    //
  }

  /**
   * 关闭
   * @param {orderData} 订单数据 如果没有参数为批量操作
   */
  handleClose(orderData?: any) {
    this.$confirm("确定关闭订单？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        const orderIds = orderData
          ? [orderData.orderId]
          : [...this.selectedIds];
        close(orderIds)
          .then(() => {
            this.getOrders(Object.assign({}, this.query, this.$route.query));
            this.$message.success("关闭成功");
          })
          .catch(err => {
            this.$message.warning(err || "关闭失败");
          });
      })
      .catch(() => {
        //
      });
  }

  triggerRemark(orderData) {
    this.currentOrder = orderData;
    this.orderIds = this.currentOrder
      ? [this.currentOrder.orderId]
      : [...this.selectedIds];

    this.toggleRemarklVisible();
  }

  /**
   * 备注
   * @param {orderData} 订单数据 如果没有参数为批量操作
   */
  handleRemarks(form?: any) {
    remarks({ orderIds: this.orderIds, ...form })
      .then(() => {
        this.getOrders(Object.assign({}, this.query, this.$route.query));
        this.toggleRemarklVisible();
        this.$message.success("备注成功");
      })
      .catch(err => {
        this.$message.warning(err || "备注失败");
      });

    // this.$prompt(`您选择了${orderIds.length}条订单`, ``, {
    //   confirmButtonText: "确定",
    //   cancelButtonText: "取消",
    //   inputType: "textarea",
    // }).then((res: any) => {

    // });
  }

  setQuicklyDate(v) {
    this.query.quicklyDate = v;
  }

  toggleDetailModal() {
    this.detailVisible = !this.detailVisible;
  }

  toggleRemarklVisible() {
    this.remarklVisible = !this.remarklVisible;
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/order/order.scss";
</style>
